# 基本网络访问和HTML解析
import sys
import urllib
import urllib.request
import io
import re
from bs4 import BeautifulSoup
from PIL import Image, ImageDraw, ImageFont
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage

# 获取网页内容
with urllib.request.urlopen("https://gitee.com/top_xiong") as response:
    info = ""
    for line in response:
        line = line.decode()
        info += line + "\n"
    
    # 使用BeautifulSoup解析HTML
    soup = BeautifulSoup(info, 'html.parser')

    # 保存HTML到文件
    with open("gitee.html", "w", encoding="utf-8") as file:
        file.write(str(soup))
    
    # 定义解析贡献数据的函数
    def parse_contribution_data(contribution_box):
        """解析贡献数据"""
        contribution_data = {
            'boxes': [],
            'total': 0,
            'max_contributions': 0,
            'months': []
        }
        
        # 查找所有贡献方块
        boxes = contribution_box.find_all('div', class_='box')
        for box in boxes:
            # 获取日期和贡献数量
            date = box.get('date', '')
            count = 0
            data_content = box.get('data-content', '')
            if data_content:
                # 从data-content中提取贡献数量
                count_match = re.search(r'(\d+)\s+次提交', data_content)
                if count_match:
                    count = int(count_match.group(1))
                    contribution_data['total'] += count
                    contribution_data['max_contributions'] = max(contribution_data['max_contributions'], count)
            
            # 添加到贡献数据中
            contribution_data['boxes'].append({
                'date': date,
                'count': count
            })
        
        # 查找月份标签
        month_labels = contribution_box.find_all('div', class_='month')
        for month in month_labels:
            contribution_data['months'].append(month.get_text(strip=True))
        
        return contribution_data
    
    # 定义绘制贡献热力图的函数
    def draw_contribution_heatmap(draw, contribution_data, img_width, img_height, font, small_font):
        """绘制贡献热力图"""
        # 热力图区域
        heatmap_x = 20
        heatmap_y = 80
        heatmap_width = img_width - 40
        heatmap_height = 120
        
        # 计算方块大小和间距
        box_size = 8
        box_margin = 2
        max_boxes_per_row = min(53, len(contribution_data['boxes']) // 7 + 1)  # 最多53周
        max_boxes_per_col = 7  # 一周7天
        
        # 绘制月份标签
        if contribution_data['months']:
            month_width = heatmap_width / len(contribution_data['months'])
            for i, month in enumerate(contribution_data['months']):
                x = heatmap_x + i * month_width
                draw.text((x, heatmap_y - 15), month, fill=(0, 0, 0), font=small_font)
        
        # 绘制星期标签
        weekdays = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
        for i, day in enumerate(weekdays):
            y = heatmap_y + i * (box_size + box_margin)
            draw.text((heatmap_x - 25, y), day, fill=(0, 0, 0), font=small_font)
        
        # 绘制贡献方块
        boxes = contribution_data['boxes']
        max_contrib = max(1, contribution_data['max_contributions'])  # 避免除以零
        
        for i, box_data in enumerate(boxes):
            # 计算位置
            week = i // 7
            day = i % 7
            
            if week >= max_boxes_per_row:
                continue
            
            x = heatmap_x + week * (box_size + box_margin)
            y = heatmap_y + day * (box_size + box_margin)
            
            # 计算颜色强度（基于贡献数量）
            count = box_data['count']
            if count == 0:
                color = (220, 220, 220)  # 浅灰色表示无贡献
            else:
                # 绿色渐变，贡献越多颜色越深
                intensity = min(1.0, count / max_contrib)
                green = int(220 - intensity * 170)  # 从浅绿到深绿
                color = (0, green, 0)
            
            # 绘制方块
            draw.rectangle([(x, y), (x + box_size, y + box_size)], fill=color, outline=None)
    
    # 查找contribution-box类的元素
    contribution_box = soup.find(class_="contribution-box")
    
    if contribution_box:
        # 解析贡献数据
        contribution_data = parse_contribution_data(contribution_box)
        contribution_text = f"最近一年贡献: {contribution_data['total']} 次"
        print(f"找到contribution-box: {contribution_text}")
        
        # 将contribution-box内容转换为图像
        img_width, img_height = 500, 250
        img = Image.new('RGB', (img_width, img_height), color=(255, 255, 255))
        draw = ImageDraw.Draw(img)
        
        # 尝试使用系统字体
        try:
            title_font = ImageFont.truetype("arial.ttf", 18)
            content_font = ImageFont.truetype("arial.ttf", 14)
            small_font = ImageFont.truetype("arial.ttf", 10)
        except IOError:
            title_font = ImageFont.load_default()
            content_font = ImageFont.load_default()
            small_font = ImageFont.load_default()
        
        # 在图像上绘制标题和贡献总数
        draw.text((10, 10), "Gitee Contribution Box", fill=(0, 0, 0), font=title_font)
        draw.text((10, 40), contribution_text, fill=(0, 0, 0), font=content_font)
        
        # 绘制贡献热力图
        draw_contribution_heatmap(draw, contribution_data, img_width, img_height, content_font, small_font)
        
        # 保存图像到内存中
        img_byte_arr = io.BytesIO()
        img.save(img_byte_arr, format='PNG')
        img_byte_arr.seek(0)
        
        # 保存图像内容供邮件使用
        img_data = img_byte_arr.getvalue()
    else:
        print("未找到contribution-box类元素")
        img_data = None

sys.exit(0)

# 发送邮件
import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr

# 配置邮箱参数
mail_host = "smtp.qq.com"  # QQ邮箱服务器地址
mail_port = 587  # 使用 TLS 端口
sender_name = "小熊"
sender = "1263083401@qq.com"  # 发件人邮箱
password = "lozxaplbufplbacg"  # 邮箱授权码（不是QQ密码！）
receivers = "xingranna@gmail.com"  # 收件人邮箱列表

# 1. 构建符合RFC标准的邮件 - 使用多部分邮件
msg = MIMEMultipart()
msg["From"] = formataddr((sender_name, sender))  # 关键修复点！
msg["To"] = receivers
msg["Subject"] = "Gitee Contribution Box 图像"

# 添加HTML正文
html_part = MIMEText("<h1>Gitee Contribution Box</h1><p>以下是您的Gitee贡献图表：</p>", "html", "utf-8")
msg.attach(html_part)

# 如果成功生成了图像，添加到邮件中
if img_data:
    img_attachment = MIMEImage(img_data)
    img_attachment.add_header('Content-Disposition', 'attachment', filename='contribution_box.png')
    img_attachment.add_header('Content-ID', '<contribution_image>')
    msg.attach(img_attachment)
    
    # 添加引用图像的HTML
    img_html = MIMEText('<p><img src="cid:contribution_image"></p>', 'html')
    msg.attach(img_html)

# 2. 发送邮件
try:
    # 创建TLS连接
    with smtplib.SMTP(mail_host, mail_port) as server:
        server.starttls()  # 关键步骤：启用TLS加密
        # server.set_debuglevel(1) 
        server.login(sender, password)
        server.sendmail(sender, receivers, msg.as_string())
        print("服务器响应:", server.noop()[1])  # 检查连接状态
        if "250" in server.noop()[1].decode():
            print("邮件确认已送达服务器")
except Exception as e:
    print(f"邮件发送失败: {e}")